package com.example.feidaolumanager.pages.ui.task

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material.icons.filled.Sensors
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.TabRowDefaults.SecondaryIndicator
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.example.feidaolumanager.databinding.FragmentTaskBinding
import com.example.feidaolumanager.pojo.Task
import com.example.feidaolumanager.pojo.User
import com.example.feidaolumanager.viewModel.MainViewModel
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import java.util.Timer
import java.util.TimerTask

class TaskFragment : Fragment() {

    private val TAG: String = this.toString()
    private var _binding: FragmentTaskBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!
    private lateinit var taskViewModel: TaskViewModel

    var user: User? = null
    private val simpleDateFormat = SimpleDateFormat(
        "yyyy-MM-dd HH:mm:ss", Locale.CHINA
    )

    @OptIn(
        ExperimentalMaterial3Api::class
    )
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        taskViewModel = ViewModelProvider(this)[TaskViewModel::class.java]

        _binding = FragmentTaskBinding.inflate(
            inflater, container, false
        )
        val root: View = binding.root

        val composeView: ComposeView = binding.tvCompose

        user = activity?.intent?.getSerializableExtra(
            "user"
        ) as User?

        if (user != null) {
            taskViewModel.getTask(
                user!!
            )
        } else {
            Log.e(
                "任务", "用户信息异常的为空"
            )
        }

        composeView.setContent {

            Scaffold(topBar = {
                TopAppBar(
                    title = {
                        Text(
                            "任务",
                            color = Color.White,
                            fontWeight = FontWeight.W800,
                            fontSize = 20.sp
                        )
                    },
                    modifier = Modifier,
                    colors = TopAppBarDefaults.smallTopAppBarColors(
                        containerColor = Color(
                            0, 179, 98
                        )
                    ),
                    navigationIcon = {
                        IconButton(onClick = {
                            findNavController().popBackStack()
                        }) {
                            Icon(
                                Icons.AutoMirrored.Filled.ArrowBack, null, tint = Color.White
                            )
                        }
                    },
                )
            }) { paddingValues ->
                var currentSelectedTab by remember {
                    mutableIntStateOf(
                        0
                    )
                }

                val tabList = listOf(
                    "未完成", "已完成", "已过期"
                )

                Column(
                    modifier = Modifier
                        .padding(
                            paddingValues = paddingValues
                        )
                        .background(color = Color(246, 246, 246))
                ) {
                    TabRow(selectedTabIndex = currentSelectedTab, indicator = {
                        SecondaryIndicator(
                            Modifier.tabIndicatorOffset(it[currentSelectedTab]),
                            color = Color(0, 179, 98)
                        )
                    }, divider = {

                    }) {
                        tabList.forEachIndexed { index, item ->
                            Tab(selected = currentSelectedTab == index, onClick = {
                                currentSelectedTab = index
                            }) {
                                Text(
                                    text = item,
                                    fontSize = 16.sp,
                                    fontWeight = FontWeight.Normal,
                                    color = if (index == currentSelectedTab) Color(
                                        0, 179, 98
                                    ) else Color.Black,
                                    modifier = Modifier.padding(all = 10.dp)
                                )
                            }
                        }
                    }


                    val lazyListState = rememberLazyListState()

                    LazyColumn(
                        state = lazyListState,
                        modifier = Modifier.fillMaxSize()
                    ) {
                        items(
                            taskViewModel.tasks.value
                        ) { task ->

                            when (currentSelectedTab) {
                                0 -> {
                                    if (task.state == 0) {
                                        TaskItem(
                                            task = task, user
                                        )
                                    }
                                }

                                1 -> {
                                    if (task.state == 1) {
                                        TaskItem(
                                            task = task, user
                                        )
                                    }
                                }

                                2 -> {
                                    if (task.state == 2) {
                                        TaskItem(
                                            task, user
                                        )
                                    }
                                }

                                else -> {}
                            }

                        }
                    }
                }
            }


        }
        return root
    }

    @Composable
    private fun TaskItem(
        task: Task, user: User?
    ) {
        Column(modifier = Modifier
            .clickable {
                Log.e(
                    "任务", "点击了任务${task.state}"
                )

            }
            .padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 8.dp)
            .clip(RoundedCornerShape(6.dp))
            .background(color = Color.White)) {

            Spacer(
                modifier = Modifier.height(10.dp)
            )
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
            ) {
                Icon(
                    imageVector = Icons.Default.LocationOn,
                    contentDescription = "位置小图标",
                    tint = Color(0, 179, 98),
                    modifier = Modifier
                        .padding(horizontal = 6.dp)
                        .size(20.dp)
                )

                Text(
                    text = task.name.split("工地")[0], fontSize = 14.sp,
                    fontWeight = FontWeight.Normal
                )
            }
            Spacer(modifier = Modifier.height(10.dp))

            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
            ) {
                Icon(
                    imageVector = Icons.Default.Sensors,
                    contentDescription = "电话小图标",
                    tint = Color(0, 179, 98),
                    modifier = Modifier
                        .padding(horizontal = 6.dp)
                        .size(20.dp)
                )

                Text(text = task.name.split(":")[1] + "ug/m³", color = Color.Red)
            }

            Spacer(modifier = Modifier.height(10.dp))
            HorizontalDivider()

            Row(
                horizontalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(all = 10.dp)
            ) {


                when (task.state) {
                    2 -> {
                        Text(text = "预警时间:")
                    }

                    0 -> {
                        Text(text = "处理期限:")
                    }

                    else -> {

                    }
                }

                var addTime: Date? = simpleDateFormat.parse(
                    task.addtime
                )

                val calendar = Calendar.getInstance()

                // 使用 日历对象给添加时间加上2小时
                if (addTime != null) {
                    Log.e(
                        TAG, "TaskItem: 成功给日历赋值"
                    )
                    calendar.time = addTime
                } else {
                    Log.e(
                        TAG, "TaskItem: 任务创建时间获取失败"
                    )
                    return
                }

                calendar.add(
                    Calendar.HOUR, 2
                )

                addTime = calendar.time
                var timeGapString by remember {
                    mutableStateOf("")
                }

                var timeGap by remember {
                    mutableLongStateOf(0L)
                }


                if (addTime.after(Date()) && task.state == 0) {
                    DisposableEffect(key1 = Unit) {
                        timeGap = addTime.time - Date().time
                        val timer = Timer()
                        timer.schedule(
                            object : TimerTask() {
                                override fun run() {
                                    timeGap -= 1000
                                    timeGapString =
                                        (timeGap / 1000 / 60 / 60).toString() + ":" + (timeGap / 1000 / 60 % 60) + ":" + (timeGap / 1000 % 60)

                                    if (timeGap <= 0) {
                                        // 定时的终点，去掉定时
                                        timer.cancel()
                                    }
                                }
                            }, 0, 1000
                        )
                        onDispose { }
                    }

                    Text(text = if (timeGap > 0) timeGapString else "")
                } else if (task.state == 2) {

                    Text(text = task.addtime)
                    Log.e(
                        TAG, "TaskItem: 当前任务已经过来可以处理的时间:$task"
                    )
                }
            }

            // 只有已过期的任务没有按钮
            if (task.state == 2) return

            Row(
                horizontalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier.fillMaxWidth()
            ) {
                Spacer(modifier = Modifier.width(10.dp))
                Button(
                    onClick = {
                        if (task.state == 1) {
                            // 跳转到详情界面，不销毁当前界面
                            this@TaskFragment.startActivityForResult(
                                Intent(
                                    activity, RectificationResultsActivity::class.java
                                )
                                    .putExtra(
                                        "task", task
                                    )
                                    .putExtra(
                                        "user", user
                                    ), 1
                            )
                        } else if (task.state == 0) {
                            // 跳转到整改界面，不销毁当前界面
                            this@TaskFragment.startActivityForResult(
                                Intent(
                                    activity, RectificationResultsActivity::class.java
                                ).putExtra("task", task).putExtra("user", user), 1
                            )
                        }
                    },
                    colors = ButtonDefaults.buttonColors(containerColor = Color(0, 179, 98)),
                    modifier = Modifier.padding(end = 10.dp)
                ) {
                    Text(text = "点击处理")
                }
            }

        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onDetach() {
        super.onDetach()
        ViewModelProvider(requireActivity())[MainViewModel::class.java].ifShowMenu.value = true
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        Log.e(TAG, "onActivityResult: haha $resultCode")
        when (requestCode) {
            1 -> {
                user?.let { taskViewModel.getTask(user = it) }
            }

            else -> {
                Log.d(TAG, "onActivityResult: 没有处理的返回值$requestCode,$resultCode")
            }
        }
    }
}